import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store'

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../components/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../components/Register.vue')
  },
  
  //首页
  {
    path: '/home',
    name: "首页",
    meta: { title: '首页' },
    children:[
      {
        path: '/student',
        name: '学生',
        meta: { title: '学生' },
        component: () => import('../views/layout/components/Student.vue')
      },
      {
        path: '/personal',
        name: '个人详情',
        meta: { title: '个人详情' },
        component: () => import('../views/layout/components/Personal.vue')
      },
      {
        path: '/homepage',
        name: '主体',
        meta: { title: '主体' },
        component: () => import('../views/layout/components/Homepage.vue')
      }
    ],
    
    component: () => import('../views/Home.vue')
  },

  //考试
  {
    path: '/index',
    name: '主页',
    meta: { title: '主页' },
    component: () => import('../views/frontdesk/Index.vue')
  },
  {
    path: '/paperdetails',
    name: '试卷',
    meta: { title: '试卷' },
    component: () => import('../views/frontdesk/paper/PaperDetails.vue')
  },
  {
    path: '/question',
    name: '试题',
    meta: { title: '试题' },
    component: () => import('../views/frontdesk/paper/Question.vue')
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 代表从那个路径而来
  //next()代表放行 next(xxx) 强制放行的xxx的路径
  if(to.path==='/'||to.path==='/login'){
    //登录页或空路径放行
    next();
  }else{
    //获取浏览器 localStorage 里的token，没有就重定向到 login
    const tokenStr = window.localStorage.getItem('token')
    if (!tokenStr) {
      return next('/login')
    }
    //有 token 就放行
    next();
  }
})

export default router
